/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Copyright: 2011 Razor team
 *            2014 LXQt team
 * Authors:
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *   Kuzma Shapran <kuzma.shapran@gmail.com>
 *
 * Copyright: 2019 Tianjin KYLIN Information Technology Co., Ltd. *
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "ukuitaskbutton.h"
#include "ukuitaskgroup.h"
#include "ukuitaskbar.h"

//#include <UKUi/Settings>
#include "../panel/common/ukuisettings.h"

#include <QDebug>
#include <QTimer>
#include <QMenu>
#include <QAction>
#include <QContextMenuEvent>
#include <QPainter>
#include <QDrag>
#include <QMouseEvent>
#include <QMimeData>
#include <QApplication>
#include <QDragEnterEvent>
#include <QStylePainter>
#include <QStyleOptionToolButton>
#include <QDesktopWidget>

#include <unistd.h>
#include "ukuitaskgroup.h"
#include "ukuitaskbar.h"
#include "../panel/customstyle.h"
#include <KWindowSystem/KWindowSystem>
// Necessary for closeApplication()
#include <KWindowSystem/NETWM>
#include <QtX11Extras/QX11Info>

#include "../panel/iukuipanelplugin.h"
#include <QAction>
#include <QDrag>
#include <QMenu>
#include <QMouseEvent>
#include <QStylePainter>
#include <QStyleOptionToolButton>
#include <QApplication>
#include <XdgIcon>
#include <string>

#define UKUI_PANEL_SETTINGS "org.ukui.panel.settings"
#define PANELPOSITION       "panelposition"

#define PANEL_SETTINGS      "org.ukui.panel.settings"
#define PANEL_SIZE_KEY      "panelsize"
#define ICON_SIZE_KEY       "iconsize"
#define PANEL_POSITION_KEY  "panelposition"

#define ORG_UKUI_STYLE            "org.ukui.style"
#define STYLE_NAME                "styleName"

bool UKUITaskButton::m_draggging = false;

/************************************************

************************************************/
void LeftAlignedTextStyle::drawItemText(QPainter * painter, const QRect & rect, int flags
            , const QPalette & pal, bool enabled, const QString & text
            , QPalette::ColorRole textRole) const
{
    QString txt = QFontMetrics(painter->font()).elidedText(text, Qt::ElideRight, rect.width());
    return QProxyStyle::drawItemText(painter, rect, (flags & ~Qt::AlignHCenter) | Qt::AlignLeft, pal, enabled, txt, textRole);
}


/************************************************

************************************************/
UKUITaskButton::UKUITaskButton(const QString & groupName, const WindowId& window, UKUITaskBar * taskbar, QWidget *parent) :
    QToolButton(parent),
    m_sdkWindow(window),
    m_urgencyHint(false),
    m_origin(Qt::TopLeftCorner),
    m_parentTaskBar(taskbar),
    m_plugin(m_parentTaskBar->plugin()),
    m_DNDTimer(new QTimer(this))
{
    Q_ASSERT(taskbar);
    m_taskButtonStatus=NORMAL;
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    setMinimumWidth(1);
    setMinimumHeight(1);
    setToolButtonStyle(Qt::ToolButtonIconOnly);
    setAcceptDrops(true);

    updateSdkText();
    updateSdkIcon();

    m_DNDTimer->setSingleShot(true);
    m_DNDTimer->setInterval(700);
    connect(m_DNDTimer, SIGNAL(timeout()), this, SLOT(activateSdkWithDraggable()));
    connect(UKUi::Settings::globalSettings(), SIGNAL(iconThemeChanged()), this, SLOT(updateSdkIcon()));

    const QByteArray id(PANEL_SETTINGS);
    m_gsettings = new QGSettings(id);
    connect(m_gsettings, &QGSettings::changed, this, [=] (const QString &key) {
                if (key == PANEL_SIZE_KEY) {
                    updateSdkIcon();
                }
            });
}

UKUITaskButton::UKUITaskButton(QuickLaunchAction * act, IUKUIPanelPlugin * plugin, QWidget * parent)
    : QToolButton(parent),
      m_act(act),
      m_plugin(plugin)
{
    m_DNDTimer = new QTimer(this);
    m_statFlag = false;
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    /*设置快速启动栏的按键不接受焦点*/
    setFocusPolicy(Qt::NoFocus);
    setAutoRaise(true);

    setDefaultAction(m_act);
    m_act->setParent(this);

    /*设置快速启动栏的菜单项*/
    const QByteArray id(UKUI_PANEL_SETTINGS);
    m_gsettingsQuickLaunch = new QGSettings(id);
    modifyQuicklaunchMenuAction(true);
    connect(m_gsettingsQuickLaunch, &QGSettings::changed, this, [=] (const QString &key){
                if (key==PANELPOSITION) {
                    modifyQuicklaunchMenuAction(true);
                }
            });

    setContextMenuPolicy(Qt::CustomContextMenu);
    connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
            this, SLOT(customContextMenuRequestedSlot(const QPoint&)));
    m_DNDTimer->setSingleShot(true);
    m_DNDTimer->setInterval(700);
    connect(m_DNDTimer, SIGNAL(timeout()), this, SLOT(activateSdkWithDraggable()));
    m_fileName=act->m_settingsMap["desktop"];
    this->setStyle(new CustomStyle());
    repaint();

}
/************************************************

************************************************/
UKUITaskButton::~UKUITaskButton()
{
}

void UKUITaskButton::updateSdkText()
{
    QString title = WindowManager::getWindowTitle(m_sdkWindow);
    setText(title.replace("&", "&&"));
    setToolTip(title);
}

void UKUITaskButton::setLeaderWindow(const WindowId& leaderWindow) {
    m_sdkWindow = leaderWindow;
}

/* int devicePixels = m_plugin->panel()->iconSize() * devicePixelRatioF()是由ico =KWindowSystem:ico(mwindow)更改的
 * 目的是为了能够显示正确的application-x-desktop的图标的大小
 *
*/

void UKUITaskButton::updateSdkIcon()
{
    QIcon ico;
//    QString iconName;
    int mIconSize=m_plugin->panel()->iconSize();
    if (ico.isNull()) {
        ico = WindowManager::getWindowIcon(m_sdkWindow);
    }
    if (m_icon.isNull()) {
        m_icon = QIcon::fromTheme("application-x-desktop");
    }
    setIcon(ico.isNull() ? m_icon : ico);
    setIconSize(QSize(mIconSize, mIconSize));
}

void UKUITaskButton::setGroupIcon(QIcon ico)
{
    m_icon = ico;
}

void UKUITaskButton::refreshIconGeometry(QRect const & geom)
{
    QString platform = QGuiApplication::platformName();
    if(platform.startsWith(QLatin1String("wayland"),Qt::CaseInsensitive)) {
        return;
    }
    NETWinInfo info(QX11Info::connection(),
                    m_sdkWindow.toInt(),
                    (WId) QX11Info::appRootWindow(),
                    NET::WMIconGeometry,
                    0);
    NETRect const curr = info.iconGeometry();
    if (curr.pos.x != geom.x() || curr.pos.y != geom.y()
            || curr.size.width != geom.width() || curr.size.height != geom.height()) {
        NETRect nrect;
        nrect.pos.x = geom.x();
        nrect.pos.y = geom.y();
        nrect.size.height = geom.height();
        nrect.size.width = geom.width();
        info.setIconGeometry(nrect);
    }
}

/************************************************

 ************************************************/
void UKUITaskButton::dragEnterEvent(QDragEnterEvent *event)
{
    // It must be here otherwise dragLeaveEvent and dragMoveEvent won't be called
    // on the other hand drop and dragmove events of parent widget won't be called
    event->acceptProposedAction();
    if (event->mimeData()->hasFormat(mimeDataFormat())) {
        emit dragging(event->source(), event->pos());
        setAttribute(Qt::WA_UnderMouse, false);
    } else {
        m_DNDTimer->start();
    }
    QToolButton::dragEnterEvent(event);
}

void UKUITaskButton::dragMoveEvent(QDragMoveEvent * event)
{
    if (event->mimeData()->hasFormat(mimeDataFormat())) {
        emit dragging(event->source(), event->pos());
        setAttribute(Qt::WA_UnderMouse, false);
    }
}

void UKUITaskButton::dragLeaveEvent(QDragLeaveEvent *event)
{
    m_DNDTimer->stop();
    QToolButton::dragLeaveEvent(event);
}

void UKUITaskButton::dropEvent(QDropEvent *event)
{
    m_DNDTimer->stop();
    if (event->mimeData()->hasFormat(mimeDataFormat())) {
        //emit dropped(event->source(), event->pos());
        setAttribute(Qt::WA_UnderMouse, false);
    }
    //QToolButton::dropEvent(event);
}

/************************************************

 ************************************************/
void UKUITaskButton::mousePressEvent(QMouseEvent* event)
{
    const Qt::MouseButton b = event->button();

    if (Qt::LeftButton == b) {
        m_dragStartPosition = event->pos();
    }
    QToolButton::mousePressEvent(event);
}

/************************************************

 ************************************************/
void UKUITaskButton::mouseReleaseEvent(QMouseEvent* event)
{
//    if (event->button() == Qt::LeftButton)
//    {
//        if (isChecked())
//            minimizeApplication();
//        else
//        {
//            raiseApplication();
//        }
//    }
    QToolButton::mouseReleaseEvent(event);

}

/************************************************

 ************************************************/
QMimeData * UKUITaskButton::mimeData()
{
    QMimeData *mimedata = new QMimeData;
    QByteArray ba;
    QDataStream stream(&ba,QIODevice::WriteOnly);
    stream << (qlonglong)(m_window);
    mimedata->setData(mimeDataFormat(), ba);
    return mimedata;
}

/************************************************

 ************************************************/
void UKUITaskButton::mouseMoveEvent(QMouseEvent* event)
{
    if (!(event->buttons() & Qt::LeftButton)) {
        return;
    }

    if ((event->pos() - m_dragStartPosition).manhattanLength() < QApplication::startDragDistance()) {
        return;
    }

    QDrag *drag = new QDrag(this);
    drag->setMimeData(mimeData());
    QIcon ico = icon();
    QPixmap img = ico.pixmap(ico.actualSize({32, 32}));
    drag->setPixmap(img);
    switch (m_plugin->panel()->position()) {
        case IUKUIPanel::PositionLeft:
        case IUKUIPanel::PositionTop:
            drag->setHotSpot({0, 0});
            break;
        case IUKUIPanel::PositionRight:
        case IUKUIPanel::PositionBottom:
            drag->setHotSpot(img.rect().bottomRight());
            break;
    }
    m_draggging = true;
    drag->exec();

    // if button is dropped out of panel (e.g. on desktop)
    // it is not deleted automatically by Qt
    drag->deleteLater();
    m_draggging = false;

    QAbstractButton::mouseMoveEvent(event);
}

void UKUITaskButton::activateSdkWithDraggable()
{
    // raise app in any time when there is a drag
    // in progress to allow drop it into an app
    qDebug()<<Q_FUNC_INFO<<m_sdkWindow<<WindowManager::getWindowTitle(m_sdkWindow);
    if (m_statFlag) {
        raiseSdkApplication();
        WindowManager::activateWindow(m_sdkWindow);
    }
}

/************************************************

 ************************************************/
void UKUITaskButton::raiseSdkApplication()
{
//    KWindowInfo info(m_window, NET::WMDesktop | NET::WMState | NET::XAWMState);
//    WindowInfo info = WindowManager::getwindowInfo(m_sdkWindow);
//    if (parentTaskBar()->raiseOnCurrentDesktop() && info.isMinimized()) {
//        KWindowSystem::setOnDesktop(m_window, KWindowSystem::currentDesktop());
//    } else {

//        int winDesktop = info.desktop();
//        if (KWindowSystem::currentDesktop() != winDesktop) {
//            KWindowSystem::setCurrentDesktop(winDesktop);
//        }
//    }
//    KWindowSystem::activateWindow(m_window);
    qDebug()<<Q_FUNC_INFO<<m_sdkWindow<<WindowManager::getWindowTitle(m_sdkWindow);
    WindowManager::activateWindow(m_sdkWindow);
    setSdkUrgencyHint(false);
}

void UKUITaskButton::minimizeSdkApplication()
{
    WindowManager::minimizeWindow(m_sdkWindow);
}


void UKUITaskButton::closeApplication()
{
    // FIXME: Why there is no such thing in KWindowSystem??
    WindowManager::closeWindow(m_sdkWindow);
}

void UKUITaskButton::setUrgencyHint(bool set)
{
    if (m_urgencyHint == set) {
        return;
    }

    if (!set) {
        KWindowSystem::demandAttention(m_window, false);
    }

    m_urgencyHint = set;
    setProperty("urgent", set);
    style()->unpolish(this);
    style()->polish(this);
    update();
}

void UKUITaskButton::setSdkUrgencyHint(bool set)
{
    if (m_urgencyHint == set) {
        return;
    }

    if (!set) {
        WindowManager::activateWindow(m_sdkWindow);
    }

    m_urgencyHint = set;
    setProperty("urgent", set);
    style()->unpolish(this);
    style()->polish(this);
    update();
}

bool UKUITaskButton::isOnDesktop(int desktop) const
{
    return KWindowInfo(m_window, NET::WMDesktop).isOnDesktop(desktop);
}

bool UKUITaskButton::isOnCurrentScreen() const
{
    return QApplication::desktop()->screenGeometry(parentTaskBar()).intersects(KWindowInfo(m_window, NET::WMFrameExtents).frameGeometry());
}

bool UKUITaskButton::isMinimized() const
{
    return KWindowInfo(m_window,NET::WMState | NET::XAWMState).isMinimized();
}

bool UKUITaskButton::isSdkMinimized() const
{
    WindowInfo info = WindowManager::getwindowInfo(m_sdkWindow);
    qDebug()<<Q_FUNC_INFO<<info.isMinimized();
    return info.isMinimized();
}

bool UKUITaskButton::isSdkFocusState() const
{
    WindowInfo info = WindowManager::getwindowInfo(m_sdkWindow);
    qDebug()<<Q_FUNC_INFO<<info.isActive();
    return info.isActive();
}


Qt::Corner UKUITaskButton::origin() const
{
    return m_origin;
}

void UKUITaskButton::setOrigin(Qt::Corner newOrigin)
{
    if (m_origin != newOrigin) {
        m_origin = newOrigin;
        update();
    }
}

void UKUITaskButton::setAutoRotation(bool value, IUKUIPanel::Position position)
{
    if (value) {
        switch (position) {
            case IUKUIPanel::PositionTop:
            case IUKUIPanel::PositionBottom:
                setOrigin(Qt::TopLeftCorner);
                break;

            case IUKUIPanel::PositionLeft:
                setOrigin(Qt::BottomLeftCorner);
                break;

            case IUKUIPanel::PositionRight:
                setOrigin(Qt::TopRightCorner);
                break;
        }
    } else {
        setOrigin(Qt::TopLeftCorner);
    }
}

void UKUITaskButton::enterEvent(QEvent *)
{
    m_taskButtonStatus=HOVER;
    update();
}

void UKUITaskButton::leaveEvent(QEvent *)
{
    m_taskButtonStatus=NORMAL;
    update();
}

/*在paintEvent中执行绘图事件会造成高分屏下图片模糊
 * 高分屏的图片模糊问题大概率与svg/png图片无关
 * */
void UKUITaskButton::paintEvent(QPaintEvent *event)
{
        QToolButton::paintEvent(event);
        return;
}

QHash<QString,QString> UKUITaskButton::settingsMap()
{
    Q_ASSERT(m_act);
    return m_act->settingsMap();
}

/*与鼠标右键的选项有关*/
void UKUITaskButton::customContextMenuRequestedSlot(const QPoint & pos)
{
    m_plugin->willShowWindow(m_menu);
    m_menu->popup(m_plugin->panel()->calculatePopupWindowPos(mapToGlobal({0, 0}), m_menu->sizeHint()).topLeft());
}

/*调整快速启动栏的菜单项*/
void UKUITaskButton::modifyQuicklaunchMenuAction(bool direction)
{
    m_deleteAct = new QAction(QIcon::fromTheme("ukui-unfixed-symbolic"), tr("delete from quicklaunch"), this);
    connect(m_deleteAct, SIGNAL(triggered()), this, SLOT(selfRemove()));
    //addAction(m_deleteAct);
    m_menu = new QMenu(this);
    m_menu->addAction(m_act);
    m_menu->addActions(m_act->addtitionalActions());
    m_menu->addSeparator();
    m_menu->addAction(m_deleteAct);
}

void UKUITaskButton::selfRemove()
{
    emit buttonDeleted();
}

void UKUITaskButton::setTaskButtonVisible(bool visible)
{
    if(!visible) {
        this->setFixedSize(0,0);
    }
}
